/*
	The MIT License

	Copyright (c) 2010 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

#include "d3d_local.h"


const float GFX_EPSILON	=	0.001f;

struct gfx_vert_s {
		EVec3	pos;
		EVec3	normal;
		EVec2	uv;
		EVec4	color;
	};

const D3DVERTEXELEMENT9 VERTEX_DECL_GFX[] = {
		{ 0, offsetof(gfx_vert_s,	pos		), D3DDECLTYPE_FLOAT3,	D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION,	0 },
		{ 0, offsetof(gfx_vert_s,	normal	), D3DDECLTYPE_FLOAT3,	D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL,		0 },
		{ 0, offsetof(gfx_vert_s,	uv		), D3DDECLTYPE_FLOAT2,	D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD,   0 },
		{ 0, offsetof(gfx_vert_s,	color	), D3DDECLTYPE_FLOAT4,	D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR,		0 },
		D3DDECL_END()
	};

/*-----------------------------------------------------------------------------
	Scene GFX system :
-----------------------------------------------------------------------------*/

//
//	ERSGFXSystem::ERSGFXSystem
//
ERSGFXSystem::ERSGFXSystem( ERScene *scene )
{
	LOG_INIT("GFX System");
	
	this->scene	=	scene;
	gfx_fx		=	NULL;
	decl		=	NULL;
	d3ddev		=	scene->d3ddev;

	ReloadShaders();
	
	HRCALL( d3ddev->CreateVertexDeclaration( VERTEX_DECL_GFX, &decl ) );
}


//
//	ERSGFXSystem::~ERSGFXSystem
//
ERSGFXSystem::~ERSGFXSystem( void )
{
	LOG_SHUTDOWN("GFX System");
	
	SAFE_RELEASE( decl );
	SAFE_RELEASE( gfx_fx );
}


//
//	ERSGFXSystem::ReloadShaders
//
void ERSGFXSystem::ReloadShaders( void )
{
	SAFE_RELEASE( gfx_fx );
	
	gfx_fx =	scene->rs->CompileEffect("shaders/gfx.fx");
}


//
//	ERSGFXSystem::AddGFXSprite
//
void ERSGFXSystem::AddGFXSprite( const ERSGFXSprite_s &sprite )
{
	sprites.push_back( sprite );
}


//
//	ERSGFXSystem::AddGFXStrip
//
void ERSGFXSystem::AddGFXStrip( const ERSGFXStrip_s &strip )
{
	strips.push_back( strip );
}



void ERSGFXSystem::RemoveGFXPrimitives( void )
{
	ClearGFXPrimitives();
}

//
//	ERSGFXSystem::RenderGFX
//
void ERSGFXSystem::RenderGFXTranslucent( IPxTexture target, IPxTexture depth )
{
	scene->rs->rtm->SetRenderTarget(0, target);

	RenderStrips(false);
	RenderSprites(depth, false);
}


//
//	ERSGFXSystem::RenderGFX
//
void ERSGFXSystem::RenderGFXDistortive( IPxTexture dudv_buffer, IPxTexture depth )
{
	scene->rs->rtm->SetRenderTarget(0, dudv_buffer);
	scene->rs->rtm->Clear( RS_CLEAR_COLOR, EVec4(0.5f, 0.5f, 0.5f, 0.0));

	RenderStrips(true);
	RenderSprites(depth, true);
}


//
//	ERSGFXSystem::ClearGFXPrimitives
//
void ERSGFXSystem::ClearGFXPrimitives( void )
{
	sprites.clear();
	strips.clear();
}


/*-----------------------------------------------------------------------------
	Internal stuff :
-----------------------------------------------------------------------------*/

static D3DXVECTOR4	Vec3ToDXVec4( const EVec3 &v, float w ) {
	return D3DXVECTOR4(v.x, v.y, v.z, w);
}

static D3DXVECTOR4	Vec4ToDXVec4( const EVec4 &v ) {
	return D3DXVECTOR4(v.x, v.y, v.z, v.w);
}


//
//	ERSGFXSystem::SetBlendMode
//
void ERSGFXSystem::SetBlendMode( ERSGFXBlend_t blend )
{
	uint src = D3DBLEND_SRCALPHA;
	uint dst = D3DBLEND_INVSRCALPHA;
	uint op  = D3DBLENDOP_ADD;
	if ( blend==RS_GFX_NORMAL		)	{	src = D3DBLEND_SRCALPHA;	dst = D3DBLEND_INVSRCALPHA;	op = D3DBLENDOP_ADD; }
	if ( blend==RS_GFX_ADDITIVE	)	{	src = D3DBLEND_ONE;			dst = D3DBLEND_ONE;			op = D3DBLENDOP_ADD; }
	if ( blend==RS_GFX_SUBTRACTIVE	)	{	src = D3DBLEND_ZERO;		dst = D3DBLEND_INVSRCCOLOR;	op = D3DBLENDOP_ADD; }
	if ( blend==RS_GFX_MULTIPLY		)	{	src = D3DBLEND_ZERO;		dst = D3DBLEND_SRCCOLOR;	op = D3DBLENDOP_ADD; }
	if ( blend==RS_GFX_LIGHTEN		)	{	src = D3DBLEND_DESTCOLOR;	dst = D3DBLEND_ONE;			op = D3DBLENDOP_ADD; }
	if ( blend==RS_GFX_DISTORTIVE	)	{	src = D3DBLEND_SRCALPHA;	dst = D3DBLEND_INVSRCALPHA;	op = D3DBLENDOP_ADD; }
	HRCALL( d3ddev->SetRenderState( D3DRS_SRCBLEND,		src ) );
	HRCALL( d3ddev->SetRenderState( D3DRS_DESTBLEND,	dst ) );
	HRCALL( d3ddev->SetRenderState( D3DRS_BLENDOP,		op )  );
}


int Vec4ClosestAxis ( const EVec4 &v ) {
	float x = abs(v.x);
	float y = abs(v.y);
	float z = abs(v.z);
	float s = sqrt(x*x + y*y + z*z);
	if (s==0) return 0;	// X - axis;
	x /= s;
	y /= s;
	z /= s;
	if (x >= y && x >= z) return 0;
	if (y >= x && y >= z) return 1;
	if (z >= y && z >= x) return 2;
	return 0;
}


//
//	ERSGFXSystem::AimSprite
//
void ERSGFXSystem::AimSprite( const EVec4 &_aim, const EVec4 &pos, float xsz, float ysz, float angle, EVec4 &x_axis, EVec4 &y_axis )
{
	EVec4	aim = _aim;

	//
	//	view space sprite :
	//	
	if ( Vec4Compare(aim, EVec4(0,0,0,0), GFX_EPSILON) ) {
		EVec4	tx, ty;
		tx.x = scene->view_matrix(0, 0);
		tx.y = scene->view_matrix(1, 0);
		tx.z = scene->view_matrix(2, 0);
		tx.w = 0;
		
		ty.x =scene->view_matrix(0, 1);
		ty.y =scene->view_matrix(1, 1);
		ty.z =scene->view_matrix(2, 1);
		ty.w = 0;
		
		float c = cos(angle);
		float s = sin(angle);
		
		x_axis	= xsz * (	tx * c + ty * s );
		y_axis	= ysz * (-	tx * s + ty * c );
		return;
	}
	
	//
	//	sprite aimed to a point :
	//
	if ( Vec4IsPoint(aim, GFX_EPSILON) ) {
		aim = pos - aim;
	}

	//
	//	aim sprite along specified direction :
	//	
	aim.w = 0;
	aim = Vec4Normalize(aim);
	
	EVec4	up = EVec4(0,0,1,0);
	if (aim.z==1) {
		up	=	EVec4(0,1,0,0);
	}
	
	EVec4	side = Vec4Cross3(up, aim);
	up			 = Vec4Cross3(aim, side);
	EVec4	tx, ty;
	tx	=	Vec4Normalize( side );
	ty	=	Vec4Normalize( up );
	
	float c = cos(angle);
	float s = sin(angle);
	
	x_axis	= xsz * (	tx * c + ty * s );
	y_axis	= ysz * (-	tx * s + ty * c );
	return;
}


//
//	ERSGFXSystem::RenderSprites
//
void ERSGFXSystem::RenderSprites( IPxTexture depth_buffer, bool rend_dudv )
{
	if (!gfx_fx) return;
	
	uint w, h;
	scene->rs->GetScreenSize(w, h);

	HRCALL( d3ddev->SetVertexDeclaration( decl ) );

	if (!SUCCEEDED( gfx_fx->SetTechnique("tech_sprite") ))  {
		return;
	}

	gfx_fx->SetBool("distortion",	rend_dudv);
	
	EVec4	view_axis_x	=	Matrix4Transform( EVec4(1,0,0,0), Matrix4Inverse(scene->view_matrix) );
	EVec4	view_axis_y	=	Matrix4Transform( EVec4(0,1,0,0), Matrix4Inverse(scene->view_matrix) );
	
	D3DXHANDLE	matrix_wvp			=	gfx_fx->GetParameterByName(NULL, "matrix_wvp"			);
	D3DXHANDLE	matrix_wv			=	gfx_fx->GetParameterByName(NULL, "matrix_wv"			);
	D3DXHANDLE	sprite_pos			=	gfx_fx->GetParameterByName(NULL, "sprite_pos"			);
	D3DXHANDLE	sprite_axis_x		=	gfx_fx->GetParameterByName(NULL, "sprite_axis_x"		);
	D3DXHANDLE	sprite_axis_y		=	gfx_fx->GetParameterByName(NULL, "sprite_axis_y"		);
	D3DXHANDLE	sprite_color		=	gfx_fx->GetParameterByName(NULL, "sprite_color"			);
	D3DXHANDLE	sprite_width		=	gfx_fx->GetParameterByName(NULL, "sprite_width"			);
	D3DXHANDLE	tex_src				=	gfx_fx->GetParameterByName(NULL, "tex_src"				);
	D3DXHANDLE	tex_depth			=	gfx_fx->GetParameterByName(NULL, "tex_depth"			);
	D3DXHANDLE	anim_offset			=	gfx_fx->GetParameterByName(NULL, "anim_offset"		);
	D3DXHANDLE	anim_frame_num		=	gfx_fx->GetParameterByName(NULL, "anim_frame_num"	);
	
	EMatrix4	wvp	=	scene->view_matrix * scene->proj_matrix;
	EMatrix4	wv	=	scene->view_matrix;
	
	gfx_fx->SetMatrix( matrix_wvp, &D3DXMATRIX( wvp.Ptr() ) );
	gfx_fx->SetMatrix( matrix_wv,  &D3DXMATRIX( wv.Ptr() ) );
	gfx_fx->SetTexture( tex_depth, depth_buffer.To<ED3DBaseTexture>()->GetD3DTexture() );
	gfx_fx->SetVector("rcp_screen_size", &D3DXVECTOR4(1.0f/w, 1.0f/h, 0, 0));

	//
	//	render sprites :
	//	
	uint num_passes;
	if (SUCCEEDED( gfx_fx->Begin(&num_passes, 0) )) {

		for (uint pass=0; pass<num_passes; pass++) {
			gfx_fx->BeginPass(pass);	
		
			for (uint i=0; i<sprites.size(); i++) {	
			
				//	read params :	
				ERSGFXSprite_s	*sp	=	&sprites[i];
				
				if (rend_dudv && sp->blend_mode!=RS_GFX_DISTORTIVE) {
					continue;
				}
				if (!rend_dudv && sp->blend_mode==RS_GFX_DISTORTIVE) {
					continue;
				}
				
				EVec4 x_axis, y_axis;
				EVec4 pos	=	Vec3ToPoint4(sp->pos);
				AimSprite( sp->aim, pos, sp->x_size, sp->y_size, sp->angle, x_axis, y_axis );
				
				IPxTexture	tex	=	scene->rs->txm->RegisterTexture( sp->texture );
				
				gfx_fx->SetTexture( tex_src, tex.To<ED3DBaseTexture>()->GetD3DTexture() );

				gfx_fx->SetVector( sprite_pos		,	&Vec3ToDXVec4( sp->pos, 1 )	);
				gfx_fx->SetVector( sprite_axis_x	,	&Vec4ToDXVec4( x_axis )		);
				gfx_fx->SetVector( sprite_axis_y	,	&Vec4ToDXVec4( y_axis )		);
				gfx_fx->SetVector( sprite_color		,	&Vec4ToDXVec4( sp->color )	);
				
				float num_frames	=	tex->GetWidth() / tex->GetHeight();
				gfx_fx->SetFloat ( anim_offset		,	sp->anim_offset	);
				gfx_fx->SetFloat ( anim_frame_num	,	num_frames		);
				
				SetBlendMode( sp->blend_mode );
				
				//	draw sprite :
				gfx_fx->CommitChanges();
			
				DrawSprite( *sp );
			}
			
			gfx_fx->EndPass();
		}
		
		gfx_fx->End();
	}
}


//
//	ERSGFXSystem::RenderSprites
//
void ERSGFXSystem::RenderStrips( bool rend_dudv )
{
	if (!gfx_fx) return;
	
	uint w, h;
	scene->rs->GetScreenSize(w, h);

	HRCALL( d3ddev->SetVertexDeclaration( decl ) );

	if (!SUCCEEDED( gfx_fx->SetTechnique("tech_strip") ))  {
		return;
	}

	gfx_fx->SetBool("distortion",	rend_dudv);
	
	D3DXHANDLE	matrix_wvp			=	gfx_fx->GetParameterByName(NULL, "matrix_wvp"		);
	D3DXHANDLE	matrix_wv			=	gfx_fx->GetParameterByName(NULL, "matrix_wv"		);
	D3DXHANDLE	strip_color			=	gfx_fx->GetParameterByName(NULL, "strip_color"		);
	D3DXHANDLE	tex_src				=	gfx_fx->GetParameterByName(NULL, "tex_src"			);
	D3DXHANDLE	anim_offset			=	gfx_fx->GetParameterByName(NULL, "anim_offset"		);
	D3DXHANDLE	anim_frame_num		=	gfx_fx->GetParameterByName(NULL, "anim_frame_num"	);
	
	EMatrix4	wvp	=	scene->view_matrix * scene->proj_matrix;
	EMatrix4	wv	=	scene->view_matrix;
	
	gfx_fx->SetMatrix( matrix_wvp, &D3DXMATRIX( wvp.Ptr() ) );
	gfx_fx->SetMatrix( matrix_wv,  &D3DXMATRIX( wv.Ptr() ) );
	gfx_fx->SetVector("rcp_screen_size", &D3DXVECTOR4(1.0f/w, 1.0f/h, 0, 0));
	
	//
	//	render strips :
	//	
	uint num_passes;
	if (SUCCEEDED( gfx_fx->Begin(&num_passes, 0) )) {

		for (uint pass=0; pass<num_passes; pass++) {
			gfx_fx->BeginPass(pass);	
		
			for (uint i=0; i<strips.size(); i++) {	
			
				//	read params :	
				ERSGFXStrip_s	*st	=	&strips[i];
				
				if ( rend_dudv && st->blend_mode!=RS_GFX_DISTORTIVE) {	continue;	}
				if (!rend_dudv && st->blend_mode==RS_GFX_DISTORTIVE) {	continue;	}
				
				IPxTexture	tex	=	scene->rs->txm->RegisterTexture( st->texture );
				gfx_fx->SetTexture( tex_src, tex.To<ED3DBaseTexture>()->GetD3DTexture() );

				float num_frames	=	tex->GetWidth() / tex->GetHeight();
				gfx_fx->SetVector( strip_color		,	&Vec4ToDXVec4( st->color )	);
				gfx_fx->SetFloat ( anim_offset		,	st->anim_offset				);
				gfx_fx->SetFloat ( anim_frame_num	,	num_frames					);
				
				SetBlendMode( st->blend_mode );
				
				//	draw sprite :
				gfx_fx->CommitChanges();
			
				DrawStrip( *st );
			}
			
			gfx_fx->EndPass();
		}
		
		gfx_fx->End();
	}
}


//
//	ERSGFXSystem::DrawSprite
//
void ERSGFXSystem::DrawSprite( const ERSGFXSprite_s &sprite )
{
	gfx_vert_s	verts[4];
	
	verts[0].pos	=	EVec3(+1,+1, 0);
	verts[0].color	=	EVec4( 0, 0, 0, 0);
	verts[0].normal	=	EVec3( 0, 0, 0);
	verts[0].uv		=	EVec2( 1, 0);
	
	verts[1].pos	=	EVec3(-1,+1, 0);
	verts[1].color	=	EVec4( 0, 0, 0, 0);
	verts[1].normal	=	EVec3( 0, 0, 0);
	verts[1].uv		=	EVec2( 0, 0);
	
	verts[2].pos	=	EVec3(-1,-1, 0);
	verts[2].color	=	EVec4( 0, 0, 0, 0);
	verts[2].normal	=	EVec3( 0, 0, 0);
	verts[2].uv		=	EVec2( 0, 1);
	
	verts[3].pos	=	EVec3(+1,-1, 0);
	verts[3].color	=	EVec4( 0, 0, 0, 0);
	verts[3].normal	=	EVec3( 0, 0, 0);
	verts[3].uv		=	EVec2( 1, 1);
	
	HRCALL( d3ddev->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, &verts, sizeof(verts[0])) );
}


//
//	ERSGFXSystem::DrawStrip
//
void ERSGFXSystem::DrawStrip( const ERSGFXStrip_s &strip )
{
	if ( strip.num_points < 2 ) {
		return;	//	TODO : Warning?
	}
	
	if ( strip.num_points > RS_GFX_MAX_STRIP_POINTS ) {
		return;
	}

	gfx_vert_s	verts[2*RS_GFX_MAX_STRIP_POINTS];
	
	float	rcp_num		=	1.0f / (strip.num_points-1);
	uint	n			=	strip.num_points;
	
	for (uint i=0; i<strip.num_points; i++) {
		gfx_vert_s *vx0 = &verts[i*2+0];
		gfx_vert_s *vx1 = &verts[i*2+1];
		
		vx0->color	=	EVec4(0,0,0,0);
		vx0->normal	=	EVec3(0,0,0);
		vx0->uv		=	EVec2(rcp_num * i, 0);
		
		vx1->color	=	EVec4(0,0,0,0);
		vx1->normal	=	EVec3(0,0,0);
		vx1->uv		=	EVec2(rcp_num * i, 1);
		
		//	strip aiming stuff :
		EVec3	p0	=	strip.points[i];	//	previous
		EVec3	p1	=	strip.points[i];	//	current
		EVec3	p2	=	strip.points[i];	//	next
		
		if (i!=0)	{ p0 = strip.points[i-1]; }
		if (i!=n-1)	{ p2 = strip.points[i+1]; }


		EVec3	v0	=	p2 - p0;
		EVec3	v1	=	Vec4ToVec3( strip.aim );
		
		if ( Vec4IsPoint( strip.aim, GFX_EPSILON ) ) {
			v1 = v1 - p1;
		}
		if ( Vec4Compare(strip.aim, EVec4(0,0,0,0), GFX_EPSILON) ) {
			v1 = p1 - Vec4ToPoint3(scene->view_position);
		}
		EVec3	v2	=	Vec3Normalize( Vec3Cross(v0, v1) ) * strip.width * 0.5;

		
		vx0->pos	=	p1 + v2;
		vx1->pos	=	p1 - v2;
	}
	
	HRCALL( d3ddev->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2*n-2, &verts, sizeof(verts[0])) );
}

